import Vue from 'vue'
import Router from 'vue-router'
import Home from './components/Home.vue'
import state from './state'
import Tickets from './components/Tickets'
import NewTicket from './components/NewTicket'
import Ticket from './components/Ticket'


Vue.use(Router)

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/faq',
    name: 'faq',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ './components/FAQ.vue')
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      guest: true,
    },
    component: () => import(/* webpackChunkName: "login" */ './components/Login.vue')
  },
  {
    path: '/tickets',
    name: 'tickets',
    meta: {
      private: true,
    },
    component: () => import(/* webpackChunkName: "tickets" */ './components/TicketsLayout.vue'),
    /*
    由于第一个子路由是空字符串，在解析父路由时它将成为默认路由。这意味着你应该将父路由的名称（'tickets' ）转移给它。
    */
    children: [{
      path: '',
      name: 'tickets',
      component: Tickets,
    }, {
      path: 'new',
      name: 'new-ticket',
      component: NewTicket,
    }, {
      path: ':id',
      name: 'ticket',
      component: Ticket,
      props: true,
    }]
  },
  {
    path: '*',
    component: () => import('./components/NotFound.vue'),
  },
]

const router = new Router({
  mode: 'history',
  routes,
  scrollBehavior(to, from, savePosition) {
    if (savePosition) {
      return savePosition
    }
    if (to.hash) {
      return { selector: to.hash }
    }
    return { x: 0, y: 0 }
  }
})

router.beforeEach((to, from, next) => {
  // 我们不应单纯依赖目标路由，而是应该检查所有匹配的嵌套路由对象。幸运的是，每个路由对象都可以使用matched 属性访问这些路由对象的列表。然后，可以使用some 数组方法来验证至少有一个路由对象具有所需的元属性。
  // 如果需要登录后访问，切用户没登录，就跳转到登录页
  if (to.matched.some(r => r.meta.private) && !state.user) {
    // 如果登录成功，需要跳转会用户当初浏览的界面,所以跳转登录页需要带上当前URL
    next({
      name: 'login',
      params: {
        wantedRoute: to.fullPath,
      }
    })
    return
  }
  // 如果你已经登录，可以尝试打开登录URL——你应该会立即被重定向到主页
  if (to.matched.some(r => r.meta.guest) && state.user) {
    next({ name: 'home' })
    return
  }
  next()
})

export default router